/// 工具函数模块

/// 脱敏token,只显示前后几位
#[allow(dead_code)]
pub fn mask_token(token: &str) -> String {
    if token.len() <= 10 {
        return "***".to_string();
    }
    format!("{}...{}", &token[..5], &token[token.len()-5..])
}

/// 脱敏邮箱地址
pub fn mask_email(email: &str) -> String {
    if let Some(at_pos) = email.find('@') {
        let (name, domain) = email.split_at(at_pos);
        if name.len() <= 2 {
            format!("**{}", domain)
        } else {
            format!("{}**{}", &name[..1], domain)
        }
    } else {
        // 不是邮箱格式,简单脱敏
        if email.len() <= 4 {
            "****".to_string()
        } else {
            format!("{}****", &email[..2])
        }
    }
}

/// 脱敏代理URL中的密码
pub fn mask_proxy_url(proxy: &str) -> String {
    // 匹配格式: protocol://username:password@host:port
    if let Some(at_pos) = proxy.rfind('@') {
        let (auth_part, host_part) = proxy.split_at(at_pos);
        
        // 查找密码部分
        if let Some(colon_pos) = auth_part.rfind(':') {
            let (protocol_user, _password) = auth_part.split_at(colon_pos);
            return format!("{}:***{}", protocol_user, host_part);
        }
    }
    
    // 如果无法解析,返回原值(可能不包含密码)
    proxy.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mask_token() {
        assert_eq!(mask_token("short"), "***");
        let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
        let masked = mask_token(token);
        assert!(masked.starts_with("eyJ0e"));
        assert!(masked.ends_with("1NiJ9"));
        assert!(masked.contains("..."));
    }

    #[test]
    fn test_mask_email() {
        assert_eq!(mask_email("test@example.com"), "t**@example.com");
        assert_eq!(mask_email("a@b.com"), "**@b.com");
        assert_eq!(mask_email("notanemail"), "no****");
    }

    #[test]
    fn test_mask_proxy_url() {
        let proxy = "http://user:pass123@proxy.com:8080";
        let masked = mask_proxy_url(proxy);
        assert_eq!(masked, "http://user:***@proxy.com:8080");
        
        let proxy_no_auth = "http://proxy.com:8080";
        assert_eq!(mask_proxy_url(proxy_no_auth), proxy_no_auth);
    }
}
